package cn.xshi.actuator.web;
import cn.hutool.core.collection.CollectionUtil;
import cn.xshi.actuator.constant.Constant;
import cn.xshi.actuator.param.ExecParam;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import cn.xshi.actuator.dto.ActuatorDTO;
import cn.xshi.actuator.dto.ClassLoadDTO;
import cn.xshi.actuator.dto.GcDTO;
import cn.xshi.actuator.vo.ActuatorVO;
import cn.xshi.actuator.param.ActuatorParam;
import cn.xshi.actuator.util.ActuatorUtil;
import cn.xshi.common.annotation.Auth;
import cn.xshi.common.base.BaseResult;
import cn.xshi.common.base.InitBean;
import cn.xshi.common.constant.CacheConstant;
import cn.xshi.common.util.GlobalRestTemplateUtil;
import cn.xshi.common.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
/**
 * @Desc WEB服务应用Server
 * @Author 邓纯杰
 * @CreateTime 2013-10-05 17:15:42
 */
@RestController
@RequestMapping("/actuator/server")
@Api(value = "WEB服务应用Server",tags = "WEB服务应用Server",description = "WEB服务应用Server")
@Slf4j
public class ActuatorServer {

    @Resource
    ActuatorUtil actuatorUtil;

    @Resource
    GlobalRestTemplateUtil globalRestTemplateUtil;

    @Resource
    InitBean initBean;

    /**
     * 上报客户端应用信息
     * @param actuatorParam
     * @return
     */
    @PostMapping(value="/upload")
    @Auth(value = "/actuator/server/upload",authenticationType = Auth.AuthorizationType.NOT_REQUIRED_LOGIN)
    @ApiOperation(value="上报客户端应用信息", notes="上报客户端应用信息")
    public BaseResult uploadActuator(@RequestBody ActuatorParam actuatorParam){
        ActuatorVO actuatorVO = new ActuatorVO();
        BeanUtils.copyProperties(actuatorParam,actuatorVO);
        boolean res = actuatorUtil.saveActuator(actuatorVO);
        if(res){
            return BaseResult.success();
        }else{
            return BaseResult.fail();
        }
    }

    /**
     * 查询所有客户端应用
     */
    @GetMapping(value="/list")
    @Auth(value = "/actuator/server/list",authenticationType = Auth.AuthorizationType.NOT_REQUIRED_LOGIN)
    @ApiOperation(value="查询所有客户端应用", notes="查询所有客户端应用")
    public BaseResult<List<ActuatorDTO>> getActuatorList(){
        Map<String,List<ActuatorVO>> map = actuatorUtil.getActuatorList();
        List<ActuatorDTO> actuatorDTOS = new ArrayList<>();
        if(!CollectionUtil.isEmpty(map)){
            Iterator<Map.Entry<String, List<ActuatorVO>>> iterator = map.entrySet().iterator();
            while (iterator.hasNext()){
                Map.Entry<String, List<ActuatorVO>> next = iterator.next();
                ActuatorDTO actuatorDTO = new ActuatorDTO(next.getKey(),next.getValue());
                actuatorDTOS.add(actuatorDTO);
            }
        }
        return BaseResult.success(actuatorDTOS);
    }

    /**
     * 系统物理内存
     * @param request
     * @param actuatorParam
     * @return
     */
    @GetMapping("/systemInfo")
    @Auth(value = "/actuator/server/systemInfo",authenticationType = Auth.AuthorizationType.NOT_REQUIRED_LOGIN)
    @ApiOperation(value="系统物理内存", notes="系统物理内存")
    public BaseResult systemInfo(HttpServletRequest request,ActuatorParam actuatorParam) {
        //手动设置秘钥
        Map<String,String> map = new HashMap<>();
        map.put(CacheConstant.JEHC_CLOUD_KEY,initBean.getJehcCloudKey());
        map.put(CacheConstant.JEHC_CLOUD_SECURITY,initBean.getJehcCloudSecurity());
        String baseClientUri = actuatorUtil.getClientBaseUri(actuatorParam);
        if(StringUtil.isEmpty(baseClientUri)){
            return BaseResult.fail("参数不合法");
        }
        return globalRestTemplateUtil.get(baseClientUri+ Constant.ACTUATOR_SYSTEM_INFO_URI,BaseResult.class,request,globalRestTemplateUtil.setHeaders(request,map));
    }

    /**
     * 线程信息
     * @param request
     * @param actuatorParam
     * @return
     */
    @GetMapping("/thread")
    @Auth(value = "/actuator/server/thread",authenticationType = Auth.AuthorizationType.NOT_REQUIRED_LOGIN)
    @ApiOperation(value="线程信息", notes="线程信息")
    public BaseResult<Thread> thread(HttpServletRequest request,ActuatorParam actuatorParam){
        //手动设置秘钥
        Map<String,String> map = new HashMap<>();
        map.put(CacheConstant.JEHC_CLOUD_KEY,initBean.getJehcCloudKey());
        map.put(CacheConstant.JEHC_CLOUD_SECURITY,initBean.getJehcCloudSecurity());
        String baseClientUri = actuatorUtil.getClientBaseUri(actuatorParam);
        if(StringUtil.isEmpty(baseClientUri)){
            return BaseResult.fail("参数不合法");
        }
        return globalRestTemplateUtil.get(baseClientUri+ Constant.ACTUATOR_TREAD_URI,BaseResult.class,request,globalRestTemplateUtil.setHeaders(request,map));
    }

    /**
     * 类加载信息
     * @param request
     * @param actuatorParam
     * @return
     */
    @GetMapping("/classLoad")
    @Auth(value = "/actuator/server/classLoad",authenticationType = Auth.AuthorizationType.NOT_REQUIRED_LOGIN)
    @ApiOperation(value="类加载信息", notes="类加载信息")
    public BaseResult<ClassLoadDTO> classLoad(HttpServletRequest request, ActuatorParam actuatorParam){
        //手动设置秘钥
        Map<String,String> map = new HashMap<>();
        map.put(CacheConstant.JEHC_CLOUD_KEY,initBean.getJehcCloudKey());
        map.put(CacheConstant.JEHC_CLOUD_SECURITY,initBean.getJehcCloudSecurity());
        String baseClientUri = actuatorUtil.getClientBaseUri(actuatorParam);
        if(StringUtil.isEmpty(baseClientUri)){
            return BaseResult.fail("参数不合法");
        }
        return globalRestTemplateUtil.get(baseClientUri+ Constant.ACTUATOR_CLASS_LOAD_URI,BaseResult.class,request,globalRestTemplateUtil.setHeaders(request,map));
    }

    /**
     * GC信息
     * @param request
     * @param actuatorParam
     * @return
     */
    @GetMapping("/gc")
    @ApiOperation(value="GC信息", notes="GC信息")
    @Auth(value = "/actuator/server/gc",authenticationType = Auth.AuthorizationType.NOT_REQUIRED_LOGIN)
    public BaseResult<GcDTO> gc(HttpServletRequest request, ActuatorParam actuatorParam){
        //手动设置秘钥
        Map<String,String> map = new HashMap<>();
        map.put(CacheConstant.JEHC_CLOUD_KEY,initBean.getJehcCloudKey());
        map.put(CacheConstant.JEHC_CLOUD_SECURITY,initBean.getJehcCloudSecurity());
        String baseClientUri = actuatorUtil.getClientBaseUri(actuatorParam);
        if(StringUtil.isEmpty(baseClientUri)){
            return BaseResult.fail("参数不合法");
        }
        return globalRestTemplateUtil.get(baseClientUri+ Constant.ACTUATOR_GC_URI,BaseResult.class,request,globalRestTemplateUtil.setHeaders(request,map));
    }

    /**
     * 堆栈快照
     * @param request
     * @param actuatorParam
     * @return
     */
    @GetMapping("/heap/dump")
    @Auth(value = "/actuator/server/heap/dump",authenticationType = Auth.AuthorizationType.NOT_REQUIRED_LOGIN)
    @ApiOperation(value="堆栈快照导出", notes="堆栈快照导出")
    public synchronized byte[] heapDump(HttpServletRequest request,ActuatorParam actuatorParam){
        //手动设置秘钥
        Map<String,String> map = new HashMap<>();
        map.put(CacheConstant.JEHC_CLOUD_KEY,initBean.getJehcCloudKey());
        map.put(CacheConstant.JEHC_CLOUD_SECURITY,initBean.getJehcCloudSecurity());
        String baseClientUri = actuatorUtil.getClientBaseUri(actuatorParam);
        if(StringUtil.isEmpty(baseClientUri)){
            return null;
        }
        return globalRestTemplateUtil.exportForGet(baseClientUri+ Constant.ACTUATOR_HEAP_DUMP_URI,request,globalRestTemplateUtil.setHeaders(request,map));
    }

    /**
     * 导出线程快照
     * @param request
     * @param actuatorParam
     * @return
     */
    @GetMapping("/thread/dump")
    @Auth(value = "/actuator/server/thread/dump",authenticationType = Auth.AuthorizationType.NOT_REQUIRED_LOGIN)
    @ApiOperation(value="导出线程快照", notes="导出线程快照")
    public synchronized byte[] threadDump(HttpServletRequest request,ActuatorParam actuatorParam){
        //手动设置秘钥
        Map<String,String> map = new HashMap<>();
        map.put(CacheConstant.JEHC_CLOUD_KEY,initBean.getJehcCloudKey());
        map.put(CacheConstant.JEHC_CLOUD_SECURITY,initBean.getJehcCloudSecurity());
        String baseClientUri = actuatorUtil.getClientBaseUri(actuatorParam);
        if(StringUtil.isEmpty(baseClientUri)){
            return null;
        }
        return globalRestTemplateUtil.exportForGet(baseClientUri+ Constant.ACTUATOR_THREAD_DUMP_URI,request,globalRestTemplateUtil.setHeaders(request,map));
    }

    /**
     * 执行自定义命令 linux命令
     Map<String, String> params = new HashMap<String, String>();
     params.put("name", "free");
     params.put("value", "-m");
     * @return
     */
    @PostMapping("/executeExec")
    @Auth(value = "/actuator/server/executeExec",authenticationType = Auth.AuthorizationType.NOT_REQUIRED_LOGIN)
    @ApiOperation(value="执行自定义命令", notes="执行自定义命令")
    public BaseResult executeExec(HttpServletRequest request,@RequestBody ExecParam execParam){
        //手动设置秘钥
        Map<String,String> map = new HashMap<>();
        map.put(CacheConstant.JEHC_CLOUD_KEY,initBean.getJehcCloudKey());
        map.put(CacheConstant.JEHC_CLOUD_SECURITY,initBean.getJehcCloudSecurity());
        String baseClientUri = actuatorUtil.getClientBaseUri(execParam.getActuator());
        if(StringUtil.isEmpty(baseClientUri)){
            return BaseResult.fail("参数不合法");
        }
        return globalRestTemplateUtil.post(baseClientUri+ Constant.ACTUATOR_EXECUTE_EXEC_URI,BaseResult.class,execParam.getExecParams(),globalRestTemplateUtil.setHeaders(request,map));
    }
}
